package com.hl.ruoyicsmshop.service.impl;

import com.hl.ruoyicsmshop.mapper.ProductStatisticsMapper;
import com.hl.ruoyicsmshop.service.IProductStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service
public class ProductStatisticsServiceImpl implements IProductStatisticsService {

    @Autowired
    private ProductStatisticsMapper productStatisticsMapper;

    @Override
    public List<Map<String, Object>> getProductStatistics(String timeRange, List<String> monthYear, String tab) {
        LocalDate startDate = null;
        LocalDate endDate = null;

        // 根据时间范围计算起止日期
        if (timeRange != null && !timeRange.isEmpty()) {
            LocalDate today = LocalDate.now();
            switch (timeRange) {
                case "today":
                    startDate = today;
                    endDate = today;
                    break;
                case "yesterday":
                    startDate = today.minusDays(1);
                    endDate = today.minusDays(1);
                    break;
                case "last7days":
                    startDate = today.minusDays(6);
                    endDate = today;
                    break;
                case "last30days":
                    startDate = today.minusDays(29);
                    endDate = today;
                    break;
            }
        } else if (monthYear != null && monthYear.size() == 2) {
            // 处理月份范围
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            startDate = LocalDate.parse(monthYear.get(0) + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            endDate = LocalDate.parse(monthYear.get(1) + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            endDate = endDate.withDayOfMonth(endDate.lengthOfMonth());
        }

        if (startDate != null && endDate != null) {
            // 根据tab类型获取不同的统计数据
            if ("quantity".equals(tab)) {
                return productStatisticsMapper.getProductStatisticsByQuantity(startDate, endDate);
            } else {
                return productStatisticsMapper.getProductStatisticsByAmount(startDate, endDate);
            }
        }

        return null;
    }
}